//
//  BattleMainLayer.m
//  SpaceStorm
//
//  Created by 祥 雍 on 13-4-10.
//  Copyright (c) 2013年 __MyCompanyName__. All rights reserved.
//

#import "BattleMainLayer.h"
#import "Variable.h"
#import "Bullet.h"

#import "MonsterInfo.h"
#import "MonsterInfoMgr.h"
#import "ShipInfo.h"
#import "ShipInfoMgr.h"
#import "ShipVo.h"
#import "UnitProxy.h"
#import "BattleScene.h"

@implementation BattleMainLayer
@synthesize myTeam = _myTeam;
@synthesize enemiesTeam = _enemiesTeam;
@synthesize bulletCache = _bulletCache;

-(id) init
{
	if( (self=[super init])) 
    {
        
        // ask director the the window size
        size = [[CCDirector sharedDirector] winSize];
        self.anchorPoint = ccp(0, 0);

        //初始化边距值
        _gap = 100;
        _leftTopGap = screenMaxWidth / 2 - _gap / 2;
        _rightTopGap = screenMaxWidth / 2 + _gap / 2;
        _leftBottomGap = screenMaxWidth / 2 - _gap / 2;
        _rightBottomGap = screenMaxWidth / 2 + _gap / 2;
    }
	return self;
}


/**
	初始化子弹缓存
 */
-(void) initBulletCache
{
    // 初始化时就生成一定数量的子弹,以后可以重复使用 
    [self.bulletCache preBuildBulletWithId:12103 number:200];
    [self.bulletCache preBuildBulletWithId:13303 number:200];
    [self.bulletCache preBuildBulletWithId:13101 number:200];
}

/**
	初始化战斗
	@param myTeam 自己的舰队，shipId的数组
	@param enemiesTeam 敌人的舰队，shipId的数组
 */
-(void) beginFight:(CCArray*)myTeam enemiesTeam:(CCArray*)enemiesTeam
{
    //两边战舰的字典
    self.myTeam        = [NSMutableDictionary dictionaryWithCapacity:8];
    self.enemiesTeam   = [NSMutableDictionary dictionaryWithCapacity:8];
    
    //初始化自己的舰队
    int myIndex = 0;
    for(ShipVo* shipVo in [[UnitProxy sharedManager] userData].shipArray)
    {
        Ship* ship = [Ship shipWithVo:shipVo];
        ship.isTeam = YES;
        [self addChild:ship];
        [self.myTeam setObject:ship forKey:[NSString stringWithFormat:@"%d", myIndex]];
        ship.position = [self getDefaultPoint:YES index:myIndex];
//        [ship moveToNormal:ccp(ship.position.x, screenMaxHeight /2)];
        myIndex++;
    }
    
    //初始化敌人的舰队
    int enemiesIndex = 8;
    for(NSNumber* monsterId in enemiesTeam)
    {
        //创建船舰
        Ship* ship = [Ship shipWithMonsterId:[monsterId intValue]];
        ship.isTeam = NO;
        ship.rotation = -180;
        [self addChild:ship];
        [self.enemiesTeam setObject:ship forKey:[NSString stringWithFormat:@"%d", enemiesIndex]];
        ship.position = [self getDefaultPoint:NO index:enemiesIndex];
        [ship moveTo:ccp(ship.position.x, screenMaxHeight /2)];
        enemiesIndex++;
    }
    
    //初始化左右2个船舰列表
    CCArray* myArray = [CCArray array];
    for(NSString* indexKey in self.myTeam)
    {
        Ship* ship = [self.myTeam objectForKey:indexKey];
        struct ListItemVo vo;
        vo.shipId = ship.shipId;
        vo.icon = ship.prop.icon;
        vo.name = ship.prop.name;
        vo.maxArmoured = ship.prop.maxShield;
        vo.maxHp = ship.prop.maxArmoured;
        vo.maxShield = ship.prop.maxHp;
        vo.index = [indexKey intValue];
        NSValue *value = nil;
        value = [NSValue valueWithBytes:&vo objCType:@encode(struct ListItemVo)];
        [myArray addObject:value];
    }
    
    CCArray* enemiesArray = [CCArray array];
    for(NSString* indexKey in self.enemiesTeam)
    {
        Ship* ship = [self.enemiesTeam objectForKey:indexKey];
        struct ListItemVo vo;
        vo.shipId = ship.shipId;
        vo.icon = ship.prop.icon;
        vo.name = ship.prop.name;
        vo.maxArmoured = ship.prop.maxShield;
        vo.maxHp = ship.prop.maxArmoured;
        vo.maxShield = ship.prop.maxHp;
        vo.index = [indexKey intValue];
        NSValue *value = nil;
        value = [NSValue valueWithBytes:&vo objCType:@encode(struct ListItemVo)];
        [enemiesArray addObject:value];
    }

    //刷新船舰列表
    [[[BattleScene sharedLayer] uiLayer] updateList:myArray rightArray:enemiesArray];
    
    //初始化子弹管理器
    self.bulletCache = [BulletCache node];
    [self addChild:self.bulletCache];
    
    //初始化子弹缓存
    [self initBulletCache];
    
    //启动每帧更新
    [self scheduleUpdate];
}

/**
    选中一艘船，镜头跟随该船，列表选中该船，显示该船的信息
	@param ship ship的引用
 */
-(void) selectShip:(Ship*)ship
{
    //镜头跟随该船
    [[BattleScene sharedLayer].camera setFollowNode:ship];
    
    //列表选中该船
    //TODO
    
    //显示该船的信息
    [[BattleScene sharedLayer].uiLayer selectShip:ship];
}

/**
	根据船舰的逻辑位置，设置船舰被选择
	@param shipIndex 船舰的逻辑位置
 */
-(void) selectShipWithIndex:(int)shipIndex

{
    Ship* ship = nil;
    if(shipIndex < 8)//自己的船
    {
        ship = [self.myTeam objectForKey:[NSString stringWithFormat:@"%d", shipIndex]];
    }
    else//敌人的船
    {
        ship = [self.enemiesTeam objectForKey:[NSString stringWithFormat:@"%d", shipIndex]];
    }
    
    if(ship != nil)
    {
        [self selectShip:ship];
    }
}

/**
	取消船舰的选中，列表中的船舰都处于无选中状态，隐藏船的信息，镜头不跟随
 */
-(void) unselectShip
{
    //列表中的船舰都处于无选中状态
    //TODO
    
    //隐藏船的信息
    //TODO
    
    //镜头不跟随
    [[BattleScene sharedLayer].camera unFollowNode];
    
}

/**
	根据是不是自己的队伍，逻辑位置，返回默认的位置
	@param isTeam 是不是自己的队伍的
	@param index 逻辑序号
	@returns 默认的位置
 */
-(CGPoint) getDefaultPoint:(BOOL)isTeam index:(int)index
{
    int posX;
    int posY;
    CGPoint result;
    
    //计算Y轴的坐标
    if(isTeam == NO)//敌人的舰队，默认在最上方
    {
        posY = screenMaxHeight;
    }
    else//自己的舰队，默认在下放
    {
        posY = 0;
    }
    
    //计算X轴的坐标
    //查询该船得宽度
    Ship* ship = nil;
    if(isTeam == NO)//敌人的舰队
    {
        ship = [self.enemiesTeam objectForKey:[NSString stringWithFormat:@"%d", index]];
        if(ship.shipId % 2 == 0)//偶数在右边
        {
            //设置坐标
            posX = _rightTopGap + ship.prop.width / 2;
            //更新间隔
            _rightTopGap += (ship.prop.width + _gap);
        }
        else//奇数在左边
        {
            posX = _leftTopGap - ship.prop.width / 2;
            //更新间隔
            _leftTopGap -= (ship.prop.width + _gap);
        }
    }
    else
    {
        ship = [self.myTeam objectForKey:[NSString stringWithFormat:@"%d", index]];
        if(ship.shipId % 2 == 0)//偶数在右边
        {
            //设置坐标
            posX = _rightBottomGap + ship.prop.width / 2;
            //更新间隔
            _rightBottomGap += (ship.prop.width + _gap);
        }
        else//奇数在左边
        {
            posX = _leftBottomGap - ship.prop.width / 2;
            //更新间隔
            _leftBottomGap -= (ship.prop.width + _gap);
        }
    }
   
    
    //合成结果并返回
    result = ccp(posX, posY);
    return result;
}

-(void) update:(ccTime)delta 
{
    //如果有船舰选中，就更新镜头的位置，实现镜头跟随
}

/**
	处理视图模式的改变
 */
-(void) updateViewType:(BattleViewType)changeToType
{
    switch (viewType) 
    {
        case BattleViewMicroscopic://微观视图(1/1)
        {
            self.scale = microscopicScale;
            break; 
        }
        case BattleViewLocal://局部视图(1/3)
        {
            self.scale = localScale;
            break; 
        }
        case BattleViewMacroscopic://宏观视图(1/9)
        {
            self.scale = macroscopicScale;
            break; 
        }
        case BattleViewOverallSituation://全局视图(1/27)
        {
            self.scale = overallSituationScale;
            break; 
        }
        default:
            break;
    }
    CCLOG(@"主战斗层：处理视图模式改变");
}

-(void) setViewpointCenter:(CGPoint)position
{
    CGPoint newPos = ccp(-[BattleScene sharedLayer].camera.curX, -[BattleScene sharedLayer].camera.curY);
    self.position = newPos;
}

-(void)draw
{ 
    int i;
    int j;
    
    glColor4f(0.2, 0.2, 0.2, 0.2);
	glLineWidth(2.0f);
    //画大区横线
    for(i = 0; i < 4; i++)
    {
        ccDrawLine(ccp(0.0, 720 * i), ccp(2160, 720 * i));
    }
    //画大区竖线
    for(i = 0; i < 4; i++)
    {
         ccDrawLine(ccp(720 * i, 0), ccp(720 * i, 2160));
    }
    
    glColor4f(1.0, 0.6, 0.2, 0.2);
	glLineWidth(1.0f);
    //画单元横线
    for(j = 0; j < 3; j++)
    {
        for(i = 0; i < 3; i++)
        {
            ccDrawLine(ccp(0.0, 180 * (i + 1) + 720 *j), ccp(2160, 180 * (i + 1) + 720 *j));
        } 
    }
    //画单元竖线
    for(j = 0; j < 3; j++)
    {
        for(i = 0; i < 3; i++)
        {
            ccDrawLine(ccp(180 * (i + 1) + 720 *j, 0), ccp(180 * (i + 1) + 720 *j, 2160));
        } 
    }
    
    //test
    glPointSize(10); 
    ccDrawPoint(ccp(600,600));
    
    ccDrawCubicBezier(ccp(100, 0), ccp(0, 0), ccp(0, 0), ccp(600, 0), 50);
}    

- (void)dealloc
{
    if(self.myTeam != nil)
    {
        [self.myTeam removeAllObjects];
        [self.myTeam release];
        self.myTeam = nil;
    }
    
    if(self.enemiesTeam != nil)
    {
        [self.enemiesTeam removeAllObjects];
        [self.enemiesTeam release];
        self.enemiesTeam = nil;
    }
    
    [super dealloc];
    
}
@end
